﻿var app = angular.module('myApp', []);

app.controller('InputMenuController', ['$scope', 'MenuService', function ($scope, MenuService) {
    $scope.menuItem = {};

    $scope.addMenuItem = function () {
        var newItem = {
            name: $scope.menuItem.name,
            price: $scope.menuItem.price
        };

        MenuService.addMenuItem(newItem);

        $scope.menuItem.name = '';
        $scope.menuItem.price = '';
    }
}]);

app.controller('DisplayMenuController', ['$scope', 'MenuService', function ($scope, MenuService) {
    $scope.menuItems = MenuService.getMenuItems();
}]);

app.controller('TweetController', ['$scope', 'TweetService', function ($scope, TweetService) {
    
    $scope.getAllTweets = function () {
        TweetService.getAllTweets(function (data) {
            $scope.tweets = data;
        });
    };
}]);

//Angular will create one and only one instance of MenuService.  Any time we
//inject MenuService through a function parameter, Angular gives us a reference
//to the same copy it created when angular started.  Angular will NEVER create a
//new version
app.factory('MenuService', [function () {
    var menuItems = [];

    var addMenuItem = function (menuItem) {
        menuItems.push(menuItem);
    };

    var getMenuItems = function () {
        return menuItems;
    }

    return {
        addMenuItem: addMenuItem,
        getMenuItems: getMenuItems
    };
}]);

app.factory('TweetService', ['$http', function ($http) {    
    var tweets = [];

    var getAllTweets = function (callback) {

        //$http({
        //    url: 'https://ccchirper99-andy.firebaseio.com/ccchirper/tweets/.json',
        //    verb: 'GET'
        //}).success(function (data) {
        //    tweets.length = 0;
        //    for (var t in data) {
        //        tweets.push(data[t]);
        //    }

        //    callback(tweets);
        //}).error(function (data) {

        //});


        $http.get('https://ccchirper99-andy.firebaseio.com/ccchirper/tweets/.json')
            .success(function (data) {
                tweets.length = 0;
                for (var t in data) {
                    tweets.push(data[t]);
                }

                callback(tweets);
            })
            .error(function (data) {

            });
    };

    return {
        getAllTweets: getAllTweets
    };
}]);